//
//  QQClient.m
//  share
//
//  Created by Jacob on 8/4/14.
//  Copyright (c) 2014 com.haomee. All rights reserved.
//

#import "QQClient.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/TencentApiInterface.h>
#import "TencentOpenAPI/QQApiInterface.h"
#import "shareConfig.h"
#import "PlatformUserMoidel.h"

#define QQ_ACCESSTOKEN_KEY    @"com.tencent.QQ.accessToken"
#define QQ_OPENID_KEY         @"com.tencent.QQ.openId"
#define QQ_EXPIRATIONDATE_KEY @"com.tencent.QQ.expirationDate"
@interface QQClient()
{
   QQApiObject *_qqApiObject;
}
@property (nonatomic,strong) TencentOAuth *tencentOauth;
@property (nonatomic,strong) void (^successBlock)(PlatformUserMoidel *model);
@property (nonatomic,strong) void (^failedBlock)(NSString *message);
@property (nonatomic) BOOL isOauthRequest;
@property (nonatomic,strong) void (^shareSuccess)(bool isSuccess);
@end
@implementation QQClient
+ (QQClient *)sharedInstance{
    static QQClient *_sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[QQClient alloc] init];
        [_sharedInstance setup];
    });
    
    return _sharedInstance;
}
- (void)setup
{

    self.tencentOauth = [[TencentOAuth alloc] initWithAppId: QQAppkey
                                              andDelegate:self];
    if (QQRedirectUrl.length > 0) {
        self.tencentOauth.redirectURI = QQRedirectUrl;
    }
    
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:QQ_ACCESSTOKEN_KEY];
    NSString *openId = [[NSUserDefaults standardUserDefaults] objectForKey:QQ_OPENID_KEY];
    NSDate *experationDate = [[NSUserDefaults standardUserDefaults] objectForKey:QQ_EXPIRATIONDATE_KEY];
    
    if (accessToken != nil) {
        self.tencentOauth.accessToken = accessToken;
        self.tencentOauth.expirationDate = experationDate;
        self.tencentOauth.openId = openId;
    }
}
#pragma mark - Bind/unBind
-(void)getUSerInfoSuccess:(void (^)(PlatformUserMoidel *))success error:(void (^)(NSString *))errorBlock
{
    self.isOauthRequest = YES;
    self.successBlock = [success copy];
    self.failedBlock = [errorBlock copy];
    
    NSArray* permissions = [NSArray arrayWithObjects:
                            kOPEN_PERMISSION_GET_USER_INFO,
                            kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
                            kOPEN_PERMISSION_ADD_ALBUM,
                            kOPEN_PERMISSION_ADD_IDOL,
                            kOPEN_PERMISSION_ADD_ONE_BLOG,
                            kOPEN_PERMISSION_ADD_PIC_T,
                            kOPEN_PERMISSION_ADD_SHARE,
                            kOPEN_PERMISSION_ADD_TOPIC,
                            kOPEN_PERMISSION_CHECK_PAGE_FANS,
                            kOPEN_PERMISSION_DEL_IDOL,
                            kOPEN_PERMISSION_DEL_T,
                            kOPEN_PERMISSION_GET_FANSLIST,
                            kOPEN_PERMISSION_GET_IDOLLIST,
                            kOPEN_PERMISSION_GET_INFO,
                            kOPEN_PERMISSION_GET_OTHER_INFO,
                            kOPEN_PERMISSION_GET_REPOST_LIST,
                            kOPEN_PERMISSION_LIST_ALBUM,
                            kOPEN_PERMISSION_UPLOAD_PIC,
                            kOPEN_PERMISSION_GET_VIP_INFO,
                            kOPEN_PERMISSION_GET_VIP_RICH_INFO,
                            kOPEN_PERMISSION_GET_INTIMATE_FRIENDS_WEIBO,
                            kOPEN_PERMISSION_MATCH_NICK_TIPS_WEIBO,
                            nil];
    
//    [self.tencentOauth logout:self];
    [self.tencentOauth authorize:permissions inSafari:NO];
}

#pragma mark - QQSDKDelegate

- (void)tencentDidLogin
{
    [[NSUserDefaults standardUserDefaults] setObject:self.tencentOauth.accessToken forKey:QQ_ACCESSTOKEN_KEY];
    [[NSUserDefaults standardUserDefaults] setObject:self.tencentOauth.openId forKey:QQ_OPENID_KEY];
    [[NSUserDefaults standardUserDefaults] setObject:self.tencentOauth.expirationDate forKey:QQ_EXPIRATIONDATE_KEY];
    
    [[NSUserDefaults standardUserDefaults] synchronize];
    

    if(![self.tencentOauth getUserInfo]){
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"api调用失败" message:@"可能授权已过期，请重新获取" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] ;
        [alert show];
    }
}

/**
 * 登录失败后的回调
 * \param cancelled 代表用户是否主动退出登录
 */
- (void)tencentDidNotLogin:(BOOL)cancelled
{
    if (self.failedBlock) {
        self.failedBlock(@"error");
    }
    
    [self clear];
}

/**
 * 登录时网络有问题的回调
 */
- (void)tencentDidNotNetWork
{
    if (self.failedBlock) {
        self.failedBlock(@"error");
    }
    
    [self clear];
}

/**
 * 请求获得内容 当前版本只支持第三方相应腾讯业务请求
 */
- (BOOL)onTencentReq:(TencentApiReq *)req
{
    
    return YES;
}

/**
 * 响应请求答复 当前版本只支持腾讯业务相应第三方的请求答复
 */
- (BOOL)onTencentResp:(TencentApiResp *)resp
{
    
    return YES;
}
- (void)getUserInfoResponse:(APIResponse*) response {
	if (response.retCode == URLREQUEST_SUCCEED)
	{

        PlatformUserMoidel *model = [PlatformUserMoidel new];
          
            model.userId = [[NSUserDefaults standardUserDefaults] objectForKey:QQ_OPENID_KEY];
            model.avatar =response.jsonResponse[@"figureurl_qq_1"];
            model.nickname = response.jsonResponse[@"nickname"];
            model.platform = @"QQ";
            model.gender = response.jsonResponse[@"gender"];
            model.orginalData = response.jsonResponse;
		
        void (^successBlock)(PlatformUserMoidel *model) = [self.successBlock copy];

        successBlock(model);
	}
	else
    {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"操作失败" message:[NSString stringWithFormat:@"%@", response.errorMsg]
							  
													   delegate:self cancelButtonTitle:@"我知道啦" otherButtonTitles: nil];
		[alert show];

	}
    
    
    
    
}
- (void)showInvalidTokenOrOpenIDMessage{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"api调用失败" message:@"可能授权已过期，请重新获取" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
}
/**
 * add Share.
 */
-(void)shareImage:(UIImage *)image title:(NSString *)title description:(NSString *)description andImageUrl:(NSString *)ImgUrl andurl:(NSString *)url andCompletionBlock:(void (^)(BOOL))block
{
    self.isOauthRequest = NO;
    self.shareSuccess = [block copy];
    if (image==nil) {
        _qqApiObject = [QQApiNewsObject objectWithURL:[NSURL URLWithString:url?url:@""] title:title description:description previewImageURL:[NSURL URLWithString:ImgUrl]];
    } else {
        NSData *imgData = UIImageJPEGRepresentation(image, 1);
        _qqApiObject = [QQApiNewsObject objectWithURL:[NSURL URLWithString:url?url:@""] title:title description:description previewImageData:imgData];
    }

    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:_qqApiObject];
    QQApiSendResultCode sent = 0;
    if (self.isQzoneShare) {
         sent = [QQApiInterface SendReqToQZone:req];
    }else
    {
        sent = [QQApiInterface sendReq:req];
    }

    [self handleSendResult:sent];
}
-(void)getFriendships:(void (^)(BOOL, NSArray *))block
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *tocken = [user objectForKey:QQ_ACCESSTOKEN_KEY];
    NSString *uid = [user objectForKey:QQ_OPENID_KEY];
    NSString *url = [NSString stringWithFormat:@"https://graph.qq.com/relation/get_fanslist?access_token=%@&oauth_consumer_key=%@&openid=%@&format=json&reqnum=30&startindex=0&mode=1",tocken,QQAppkey,uid];
    //6046610265336839122
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request
                                               returningResponse:nil error:nil];
    NSError *error;
    NSDictionary *info = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:&error];
    if (error) {
        block(NO,nil);
        return;
    }
    NSDictionary *dic = info[@"data"];
    NSArray *friendshipsArray = dic[@"info"];
    block(YES,friendshipsArray);


}
- (BOOL)openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    if (self.isOauthRequest) {
        return [TencentOAuth HandleOpenURL:url];
    } else {
        return [QQApiInterface handleOpenURL:url delegate:self];
    }
    
}
-(void)clear
{
    self.successBlock = nil;
    self.failedBlock = nil;
}
- (void)handleSendResult:(QQApiSendResultCode)sendResult
{
    switch (sendResult)
    {
        case EQQAPIAPPNOTREGISTED:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"App未注册" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            break;
        }
        case EQQAPIMESSAGECONTENTINVALID:
        case EQQAPIMESSAGECONTENTNULL:
        case EQQAPIMESSAGETYPEINVALID:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"发送参数错误" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            break;
        }
        case EQQAPIQQNOTINSTALLED:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"未安装手Q" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            break;
        }
        case EQQAPIQQNOTSUPPORTAPI:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"API接口不支持" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            break;
        }
        case EQQAPISENDFAILD:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"发送失败" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            break;
        }
        case EQQAPIQZONENOTSUPPORTTEXT:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"空间分享不支持纯文本分享，请使用图文分享" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            break;
        }
        case EQQAPIQZONENOTSUPPORTIMAGE:
        {
            UIAlertView *msgbox = [[UIAlertView alloc] initWithTitle:@"Error" message:@"空间分享不支持纯图片分享，请使用图文分享" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [msgbox show];
            break;
        }
        default:
        {
            break;
        }
    }
}
/**
 处理来至QQ的响应
 */
- (void)onResp:(QQBaseResp *)resp
{
    void (^shareSuccess)(bool isSuccess) = [self.shareSuccess copy];
    if ([resp.result intValue] == 0) {
        shareSuccess(YES);
    } else {
        shareSuccess(NO);
    }
}
@end
